package com.young.ums.web;

import com.young.common.client.ums.UmsClientHelper;
import com.young.common.core.excel.ExcelExport;
import com.young.common.core.excel.ExcelImport;
import com.young.common.core.excel.IExcelExport;
import com.young.common.core.excel.IExcelImport;
import com.young.common.util.CommonUtil;
import com.young.common.util.Result;
import com.young.common.util.StringUtils;
import com.young.common.util.Page;
import com.young.interfaces.log.annotation.Log;
import com.young.ums.model.User;
import com.young.ums.model.Menu;
import com.young.ums.model.Navigate;
import com.young.ums.service.INavigateService;
import com.young.ums.service.IRoleNavigateService;
import com.young.ums.service.IRoleUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
* 导航资源服务
* Created by imrookie on 2018-10-8.
*/
@Controller
@RequestMapping(value = "/ums/navigate", method = {RequestMethod.GET, RequestMethod.POST})
public class NavigateController {

    @Resource(name="navigateService")
    INavigateService service;

    @Resource(name="roleNavigateService")
    IRoleNavigateService roleNavigateService;

    @Resource(name="roleUserService")
    IRoleUserService roleUserService;

    /**
    * 获取数据列表
    * @param obj
    * @param request
    * @return
    */
    @Log("查询导航资源列表")
    @RequestMapping("/getList")
    @ResponseBody
    public Object getList(Navigate obj, HttpServletRequest request) {
        List<Navigate> list = service.getList(obj);
        return Result.buildSuccess(list);
    }

    /**
    * 获取分页数据
    * @param obj
    * @param request
    * @return
    */
    @Log("分页查询导航资源列表")
    @RequestMapping("/getPage")
    @ResponseBody
    public Object getPage(Navigate obj, HttpServletRequest request) {
        Page page = CommonUtil.getPageFromRequest(request);
        List<Navigate> list = service.getPage(obj, page);
        page.setData(list);
        return page;
    }

    /**
    * 获取单条数据
    * @param id
    * @param request
    * @return
    */
    @Log("查询导航资源")
    @RequestMapping("/get")
    @ResponseBody
    public Object get(String id, HttpServletRequest request) {
        Navigate obj = service.get(id);
        return Result.buildSuccess(obj);
    }

    /**
    * 统计数量
    * @param obj
    * @param request
    * @return
    */
    @Log("统计导航资源数量")
    @RequestMapping("/count")
    @ResponseBody
    public Object count(Navigate obj, HttpServletRequest request) {
        return Result.buildSuccess(service.count(obj));
    }

    /**
    * 新增
    * @param obj
    * @param request
    * @return
    */
    @Log("新增导航资源")
    @RequestMapping("/insert")
    @ResponseBody
    public Object insert(Navigate obj, HttpServletRequest request) {
        com.young.interfaces.ums.model.User user = UmsClientHelper.getLoginUser();
        if (user != null){
            obj.setCompanyId(user.getCompanyId());
            obj.setCreateUserId(user.getId());
            obj.setUpdateUserId(user.getId());
        }
        service.insert(obj);
        return Result.buildSuccess();
    }

    /**
    * 修改
    * @param obj
    * @param request
    * @return
    */
    @Log("修改导航资源")
    @RequestMapping("/update")
    @ResponseBody
    public Object update(Navigate obj, HttpServletRequest request) {
        com.young.interfaces.ums.model.User user = UmsClientHelper.getLoginUser();
        if (user != null){
            obj.setCreateUserId(null);
            obj.setUpdateUserId(user.getId());
        }
        service.update(obj);
        return Result.buildSuccess();
    }

    /**
    * 删除
    * @param ids
    * @param id
    * @param request
    * @return
    */
    @Log("删除导航资源")
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String ids, String id, HttpServletRequest request) {
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            service.delete(idArr);
        }else if(StringUtils.isNotBlank(id)){
            service.delete(id);
        }else{
            return Result.buildFail("删除失败:待删除编号无效!");
        }
        return Result.buildSuccess();
    }

    /**
    * 导入
    * @param file
    * @param request
    * @return
    */
    @Log("导入导航资源")
    @RequestMapping("/import")
    @ResponseBody
    public Object importExcel(MultipartFile file, HttpServletRequest request) {
        try {
            if (file != null && !file.isEmpty()) {
                //excel导入处理,返回excel中的数据集合
                IExcelImport ei = new ExcelImport(file);//将文件转为ExcelImport对象
                //从excel读取数据
                List<Navigate> list = ei.getImportDataAsBean(Navigate.class);
                if (list != null && list.size() > 0){
                    int num = service.batchInsert(list);//批量插入
                    return Result.buildSuccessInfo("成功导入数据" + num + "条!");
                }else {
                    return Result.buildFail("导入失败:excel解析后结果为空!");
                }
            } else {
                return Result.buildFail("导入失败:文件为空!");
            }
        } catch (Exception e) {
            return Result.buildFail("导入失败!");
        }
    }

    /**
    * 导出
    * @param obj 查询参数
    * @param request
    * @param response
    * @throws Exception
    */
    @Log("导出导航资源")
    @RequestMapping("/export")
    public void exportExcel(Navigate obj, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Navigate> list = service.getList(obj);
        if (list != null && list.size() > 0){
            IExcelExport ee = new ExcelExport();
            ee.insertBeanList(list, Navigate.class);
            ee.write2Response(response, "excel_" + System.currentTimeMillis() + ".xls");
        }else{
            response.getWriter().write("数据为空!");
        }
    }

    /**
     * 获取菜单
     * @param request
     * @return
     */
    @Log("获取菜单")
    @RequestMapping("/getMenu")
    @ResponseBody
    public Object getMenu(HttpServletRequest request) {
        com.young.interfaces.ums.model.User user = UmsClientHelper.getLoginUser();
        if (user == null){
            return Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }
        //查询用户的角色信息
        String[] role = roleUserService.getRoleIdsByUserId(user.getId());
        if (role == null || role.length == 0){
            return Result.buildFail("您尚未关联任何角色!");
        }
        //根据角色查询导航资源
        List<Navigate> navList = roleNavigateService.getMenuNavigateListByRole(role);
        List<Menu> menuList = new LinkedList<Menu>();
        //navigate转menu
        for(Navigate n : navList){
            menuList.add(new Menu(n));
        }
        //遍历父子关系
        for(Menu m : menuList){
            if(m != null){
                for(Menu m2 : menuList){
                    if(m2 != null && m2.getParentId() != null && m2.getParentId().equals(m.getId())){
                        m.appendChild(m2);
                        m2.setParent(m);
                    }
                }
            }
        }
        //找出根节点即是树
        List<Menu> menu = new LinkedList<Menu>();
        for(Menu m : menuList){
            if(m.isRoot()){
                menu.add(m);
                m.setParent(null);
            }else{
                m.setParent(null);//清除parent,否则springmvc返回json时会报异常
            }
        }
        return Result.buildSuccess(menu);
    }

}